<script setup lang="ts">
import { ref, onMounted, watch } from 'vue'
import { Search, Edit, Delete, Picture, Refresh } from '@element-plus/icons-vue'
import type { FormInstance } from 'element-plus'
import { articleApi } from '@/apis/ArticleApi'
import { QueryArticle, ArticleView } from '@/apis/types/Article'
import { categoryApi } from '@/apis/CategoryApi'
import { tagApi } from '@/apis/TagApi'
import { Category } from '@/apis/types/Category'
import { Tag } from '@/apis/types/Tag'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'

const tableData = ref<ArticleView[]>([])
const total = ref(0)
const loading = ref(false)
const queryForm = ref<QueryArticle>({
    pageNum: 1,
    pageSize: 10,
    status: '0' //默认已发布
})

const formRef = ref<FormInstance>()

// 添加分类和标签的响应式引用
const categories = ref<Category[]>([])
const tags = ref<Tag[]>([])

// 添加路由实例
const router = useRouter()

// 获取列表数据
const getArticleList = async () => {
    loading.value = true
    try {
        const response = await articleApi.getList(queryForm.value)
        tableData.value = response.data.recordList
        total.value = response.data.total
    } catch (error) {
        ElMessage.error('获取列表数据失败')
    } finally {
        loading.value = false
    }
}

// 获取分类列表
const loadCategories = async () => {
    try {
        const response = await categoryApi.getList()
        categories.value = response.data
    } catch (error) {
        ElMessage.error('获取分类列表失败')
    }
}

// 搜索
const handleSearch = () => {
    queryForm.value.pageNum = 1
    getArticleList()
}

// 重置
const handleReset = () => {
    if (!formRef.value) return
    // 重置表单字段到初始值
    queryForm.value = {
        pageNum: 1,
        pageSize: 10,
        status: '0', // 重置为默认状态
        categoryId: undefined,
        tagId: undefined,
        date: undefined
    }
    // 清空标签列表
    tags.value = []
    // 重新获取数据
    getArticleList()
}

// 分页变化
const handlePageChange = (val: number) => {
    queryForm.value.pageNum = val
    getArticleList()
}

// 每页条数变化
const handleSizeChange = (val: number) => {
    queryForm.value.pageSize = val
    queryForm.value.pageNum = 1
    getArticleList()
}

// 编辑
const handleEdit = async (row: ArticleView) => {
    try {
        const response = await articleApi.getArticleDetail(row.id)
        if (response.code === 200) {
            // 使用 localStorage 临时存储文章数据
            localStorage.setItem('editArticle', JSON.stringify(response.data))
            // 导航到文章编辑页面
            router.push({
                name: 'Article',
                query: { id: row.id.toString() }
            })
        } else {
            ElMessage.error(response.msg || '获取文章详情失败')
        }
    } catch (error) {
        ElMessage.error('获取文章详情失败')
    }
}

// 删除
const handleDelete = (row: ArticleView) => {
    ElMessageBox.confirm('确认删除该文章吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        center: true,
        customClass: 'custom-message-box',
        confirmButtonClass: 'el-button--danger',
        cancelButtonClass: 'el-button--info',
        showClose: false
    }).then(async () => {
        try {
            const response = await articleApi.deleteArticle(row.id)
            if (response.code === 200) {
                ElMessage({
                    type: 'success',
                    message: '删除成功',
                    duration: 2000
                })
                // 如果当前页只有一条数据，且不是第一页，则跳转到上一页
                if (tableData.value.length === 1 && queryForm.value.pageNum > 1) {
                    queryForm.value.pageNum--
                }
                // 重新获取列表数据
                getArticleList()
            } else {
                ElMessage({
                    type: 'error',
                    message: response.msg || '删除失败',
                    duration: 2000
                })
            }
        } catch (error) {
            ElMessage({
                type: 'error',
                message: '删除操作异常',
                duration: 2000
            })
        }
    }).catch(() => {
        // 取消删除时的处理
        ElMessage({
            type: 'info',
            message: '已取消删除',
            duration: 2000
        })
    })
}

const formatDateTime = (dateStr: string) => {
    if (!dateStr) return '';
    const date = new Date(dateStr);
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    const hours = String(date.getHours()).padStart(2, '0');
    const minutes = String(date.getMinutes()).padStart(2, '0');
    const seconds = String(date.getSeconds()).padStart(2, '0');

    return `${year}/${month}/${day} ${hours}:${minutes}:${seconds}`;
}

onMounted(() => {
    loadCategories()
    getArticleList()

    // 监听分类变化，获取对应的标签
    watch(() => queryForm.value.categoryId, async (newCategoryId) => {
        if (!newCategoryId) {
            tags.value = []
            queryForm.value.tagId = undefined
            return
        }

        try {
            const response = await tagApi.getTags(newCategoryId)
            tags.value = response.data
        } catch (error) {
            ElMessage.error('获取标签列表失败')
        }
    })
})
</script>

<template>
    <div class="draft-container">
        <div class="draft-header">
            <h2>📋 文章管理 📋</h2>
        </div>

        <!-- 搜索区域 -->
        <el-card class="search-card">
            <el-form ref="formRef" :model="queryForm" inline>
                <el-form-item label="分类">
                    <el-select v-model="queryForm.categoryId" placeholder="请选择分类" clearable style="width: 10vw;">
                        <el-option v-for="item in categories" :key="item.id" :label="item.name" :value="item.id" />
                    </el-select>
                </el-form-item>

                <el-form-item label="标签">
                    <el-select v-model="queryForm.tagId" placeholder="请先选择分类" clearable
                        :disabled="!queryForm.categoryId" style="width: 10vw;">
                        <el-option v-for="item in tags" :key="item.id" :label="item.name" :value="item.id" />
                    </el-select>
                </el-form-item>

                <el-form-item label="日期">
                    <el-date-picker v-model="queryForm.date" type="month" placeholder="选择月份" format="YYYY年MM月"
                        value-format="YYYY/MM" style="width: 10vw;">
                        <template #default="cell">
                            <div class="el-date-table-cell" :class="{ current: cell.isCurrent }">
                                <span class="el-date-table-cell__text">{{ cell.text + 1 }}月</span>
                            </div>
                        </template>
                    </el-date-picker>
                </el-form-item>

                <el-form-item label="状态">
                    <el-select v-model="queryForm.status" placeholder="请选择状态" clearable style="width: 10vw;">
                        <el-option label="已发布" value="0" />
                        <el-option label="草稿" value="1" />
                    </el-select>
                </el-form-item>

                <el-form-item>
                    <el-button type="primary" :icon="Search" @click="handleSearch">搜索</el-button>
                    <el-button :icon="Refresh" @click="handleReset">重置</el-button>
                </el-form-item>
            </el-form>
        </el-card>

        <!-- 表格区域 -->
        <el-card class="table-card">
            <el-table v-loading="loading" :data="tableData" border stripe style="width: 100%">
                <el-table-column prop="title" label="标题" fixed="left" min-width="200" />
                <el-table-column prop="categoryName" label="分类" width="120" />
                <el-table-column prop="thumbnail" label="缩略图" width="100">
                    <template #default="{ row }">
                        <el-image :src="row.thumbnail" fit="cover" class="thumbnail-image">
                            <template #error>
                                <div class="image-slot">
                                    <el-icon>
                                        <Picture />
                                    </el-icon>
                                </div>
                            </template>
                        </el-image>
                    </template>
                </el-table-column>
                <el-table-column prop="summary" label="摘要" show-overflow-tooltip min-width="300" />
                <el-table-column prop="viewCount" label="浏览量" width="100" sortable>
                    <template #default="{ row }">
                        {{ row.viewCount || 0 }}
                    </template>
                </el-table-column>
                <el-table-column prop="createTime" label="创建时间" width="160" sortable>
                    <template #default="{ row }">
                        {{ formatDateTime(row.createTime) }}
                    </template>
                </el-table-column>
                <el-table-column fixed="right" label="操作" width="120">
                    <template #default="{ row }">
                        <el-button type="primary" :icon="Edit" circle @click="handleEdit(row)" />
                        <el-button type="danger" :icon="Delete" circle @click="handleDelete(row)" />
                    </template>
                </el-table-column>
            </el-table>

            <!-- 分页 -->
            <div class="pagination">
                <el-pagination v-model:current-page="queryForm.pageNum" v-model:page-size="queryForm.pageSize"
                    :page-sizes="[5, 10, 20, 40]" :total="total" layout="total, sizes, prev, pager, next, jumper"
                    background 
                    @size-change="handleSizeChange" @current-change="handlePageChange" />
            </div>
        </el-card>
    </div>
</template>

<style scoped>
.draft-container {
    padding: 2vw;
}

.draft-header {
    margin-bottom: 1vw;
    color: #303133;
    font-size: 2vw;
    text-align: center;
    font-weight: 600;
    background: linear-gradient(135deg, #ff80f0 0%,#409EFF  100%);
    border-radius: 2vw;
    color: #f2c05d;
}


.search-card {
    margin-bottom: 10px;
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 #ff80f0;
    background: rgb(244, 255, 225);
}

.table-card {
    margin-bottom: 2vw;
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}
.tag-item {
    margin-right: 5px;
    margin-bottom: 5px;
}

.pagination {
    margin-top: 2vw;
    display: flex;
    justify-content: flex-end;
}

:deep(.el-button) {
    margin-right: 1vw;
}
:deep(.el-button:last-child) {
    margin-right: 0;
}

.thumbnail-image {
    width: 60px;
    height: 60px;
    border-radius: 4px;
    cursor: pointer;
}

/* 美化表格样式 */
:deep(.el-table) {
    border-radius: 2vw;
    overflow: hidden;
}
</style>

<style>

</style>